import 'dart:io';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:package_info/package_info.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/pages/me/widget/me_item_cell.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/user/user_manager.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:photo_frame/widgets/custom_cupertino_alert_dialog.dart';
import 'package:url_launcher/url_launcher.dart';

class AboutMePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: commonAppBar(appLocalForContext(context).aboutTitle),
      body: Container(
          height: double.infinity,
          color: Color(0xffF2F2F2),
          padding: EdgeInsets.only(left: 16, right: 16),
          child: SafeArea(
            child: Column(children: [
              MeItemCell(
                title: appLocalForContext(context).appUpdateTitle,
                tailing: MeItemArrow(),
                action: () {
                  fetchNewVersion(context);
                },
              ),
              MeItemCell(
                title: appLocalForContext(context).deleteAllAppCacheTitle,
                tailing: MeItemArrow(),
                action: () {
                  EasyLoading.showToast(appLocal().clearCacheSuccess);
                },
              ),
              MeItemCell(
                title: appLocalForContext(context).unreg,
                tailing: MeItemArrow(),
                action: () {
                  unreg(context);
                },
              ),
              FutureBuilder<PackageInfo>(
                future: PackageInfo.fromPlatform(),
                builder: (context, snapshot) {
                  return MeItemCell(
                    title: "version: ${snapshot.data?.version ?? ""}",
                  );
                },
              ),
              Expanded(child: SizedBox()),
              CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () async {
                  await UserManager.instance.logout();
                },
                child: Container(
                  width: double.infinity,
                  height: 60,
                  decoration: BoxDecoration(
                    color: Color(0xFF3F74EF),
                    borderRadius: BorderRadius.circular(30),
                  ),
                  child: Center(
                      child: Text(
                    appLocalForContext(context).logoutTitle,
                    style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: Colors.white),
                  )),
                ),
              ),
              SizedBox(height: 20)
            ]),
          )),
    );
  }

  fetchNewVersion(BuildContext context) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    final res = await HttpManager.instance.doRequest("/info/upgrade",
        parameters: {"version": packageInfo.version}, showTost: false);
    if (res.isSuccess) {
      final url = res.data?["url"].toString() ?? "";
      final messages = res.data?["info"] ?? <String>[];
      if (url.isNotEmpty) {
        showUpdateDialog(context, messages, url);
      } else {
        EasyLoading.showToast(res.msg ?? appLocal().alreayInNewestVersion);
      }
    } else {
      EasyLoading.showToast(appLocal().alreayInNewestVersion);
    }
  }

  unreg(BuildContext context) async {
    await HttpManager.instance
        .doRequest("/info/unreg", parameters: {}, showTost: false);
    EasyLoading.showToast(appLocal().unbindSuccessful);
    UserManager.instance.logout();
  }

  showUpdateDialog(BuildContext context, List<String> messages, String url) {
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return CustomCupertinoAlertDialog(
            title: Text(
              appLocalForContext(context).hasNerVersion,
              style: TextStyle(
                  fontSize: 16,
                  color: Color(0xff333333),
                  fontWeight: FontWeight.bold),
            ),
            content: Column(
              children: [
                ...messages.map((msg) {
                  return Text(msg,
                      style: TextStyle(color: Color(0xff999999), fontSize: 14));
                }),
                SizedBox(height: 20),
              ],
            ),
            actions: [
              CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  launchUrl(
                    Uri.parse(url),
                    mode: LaunchMode.externalApplication, //设置外部浏览器打开
                  );
                  Navigator.pop(context);
                },
                child: Text(
                  appLocalForContext(context).confirm,
                  style: TextStyle(
                      fontSize: 16,
                      color: Color(0xff333333),
                      fontWeight: FontWeight.bold),
                ),
              ),
            ],
          );
        });
  }
}
